﻿package net.wangit.view.page;

import net.wangit.MapList;
import net.wangit.Page;
import net.wangit.Row;
import net.wangit.context.ActionContext;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.ServerAccessException;
import net.wangit.jdbc.Type;
import net.wangit.jdbc.util.DBHelper;
import net.wangit.util.Checker;
import net.wangit.view.unit.UnitConfigurationException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class PageFactory {

	private static Log log = LogFactory
			.getLog(net.wangit.view.page.PageFactory.class);
	private static final String SQL = "select * from UNIT where uid=?";

	public PageFactory() {
	}

	public static synchronized Page getPage(ActionContext ac, String domain,
			String unitId) {
		if (Checker.isEmpty(domain) || Checker.isEmpty(unitId)) {
			log.error((new StringBuilder(
					"empty arguments is not acceptable: domain=")).append(
					domain).append(" unitid=").append(unitId).toString());
			return null;
		}
		unitId = unitId.toLowerCase();
		PageImpl page = (PageImpl) PageCache.get(domain, unitId);
		if (page == null) {
			page = createPage(domain, unitId);
			PageCache.put(domain, unitId, page);
		}
		return page.clonePage(ac);
	}

	private static PageImpl createPage(String domain, String unitId) {
		DB db = DBHelper.getDomainDB(domain);
		MapList list;
		try {
			list = db.query(PageFactory.SQL, unitId, Type.VARCHAR);
		} catch (Exception e) {
			log.error((new StringBuilder("could not query unit in server: "))
					.append(domain).toString(), e);
			throw new ServerAccessException((new StringBuilder(
					"could not query unit in server: ")).append(domain)
					.toString());
		}
		if (Checker.isEmpty(list)) {
			log.error((new StringBuilder("page not found: ")).append(domain)
					.append("/").append(unitId).toString());
			throw new UnitConfigurationException((new StringBuilder(
					"page not found: ")).append(domain).append("/").append(
					unitId).toString());
		} else {
			Row row = list.getRow(0);
			PageImpl page = new PageImpl();
			page.setDomain(domain);
			page.setId(unitId);
			page.setSupportLog(!"0".equals(row.get("pl")));
			page.setInterceptors(row.get("pi"));
			page.setTemplate(row.get("pt"));
			page.setWindowTitle(row.get("pbt"));
			page.setHead(row.get("phe"));
			page.setBodyAttribute(row.get("pb"));
			page.setHeading(row.get("ph"));
			page.setSubheading(row.get("psh"));
			page.setCssPaths(row.get("pcp"));
			page.setHeadJsPaths(row.get("phjp"));
			page.setTailJsPaths(row.get("ptjp"));
			page.setCacheMode(row.getInt("cm", 0));
			return page;
		}
	}

}
